<template>
  <div class="menu-management">
    <div class="page-header">
      <h2>菜单管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddMenu(null)">
          <el-icon><Plus /></el-icon>新增菜单
        </el-button>
        <el-button @click="loadMenuList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="menu-table-card">
      <el-table
        :data="menuList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="tableLoading"
      >
        <el-table-column prop="title" label="菜单名称" min-width="180">
          <template #default="{ row }">
            <span>
              <el-icon v-if="row.icon"><component :is="row.icon.replace('el-icon-', '')" /></el-icon>
              {{ row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" min-width="180" />
        <el-table-column prop="component" label="组件路径" min-width="200" />
        <el-table-column prop="permission" label="权限标识" min-width="150" />
        <el-table-column prop="type" label="菜单类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.type === 0" type="success">目录</el-tag>
            <el-tag v-else-if="row.type === 1" type="primary">菜单</el-tag>
            <el-tag v-else-if="row.type === 2" type="info">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAddMenu(row)">
              <el-icon><Plus /></el-icon>添加子菜单
            </el-button>
            <el-button type="primary" link @click="handleEditMenu(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDeleteMenu(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            :props="{ children: 'children', label: 'title' }"
            node-key="id"
            default-expand-all
            placeholder="请选择上级菜单"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="menuForm.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="图标" v-if="menuForm.type !== 2">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称">
            <template #prepend>el-icon-</template>
          </el-input>
        </el-form-item>
        <el-form-item label="路由路径" prop="path" v-if="menuForm.type !== 2">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 1">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission" v-if="menuForm.type !== 0">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMenu">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Edit, 
  Delete, 
  Refresh, 
  Setting,
  Monitor,
  Folder,
  Document,
  MapLocation,
  Van,
  Money,
  DataAnalysis
} from '@element-plus/icons-vue'

// 菜单列表
const menuList = ref([])
const tableLoading = ref(false)

// 菜单表单对话框
const menuDialogVisible = ref(false)
const dialogTitle = ref('新增菜单')
const menuFormRef = ref(null)
const menuForm = reactive({
  id: null,
  parentId: null,
  type: 1,
  title: '',
  icon: '',
  path: '',
  component: '',
  permission: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const menuRules = {
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 菜单选项（用于上级菜单选择）
const menuOptions = ref([])

// 加载菜单列表
const loadMenuList = async () => {
  tableLoading.value = true
  try {
    // 实际项目中应该调用API获取菜单列表
    // const { data } = await getMenuList()
    // menuList.value = data

    // 模拟数据
    menuList.value = [
      {
        id: 1,
        parentId: null,
        type: 1,
        title: '仪表盘',
        icon: 'el-icon-Monitor',
        path: '',
        component: '../views/dashboard/DashboardView.vue',
        permission: 'dashboard:view',
        sort: 1,
        status: 1
      },
      {
        id: 2,
        parentId: null,
        type: 0,
        title: '基础数据',
        icon: 'el-icon-Folder',
        path: '/base-data',
        component: '../views/baseData/BaseDataView.vue',
        permission: '',
        sort: 2,
        status: 1,
        children: [
          {
            id: 21,
            parentId: 2,
            type: 1,
            title: '企业/承运商管理',
            icon: '',
            path: '/base-data/enterprise',
            component: '../views/baseData/EnterpriseView.vue',
            permission: 'enterprise:view',
            sort: 1,
            status: 1
          },
          {
            id: 22,
            parentId: 2,
            type: 1,
            title: '车辆档案',
            icon: '',
            path: '/base-data/vehicle',
            component: '../views/baseData/VehicleView.vue',
            permission: 'vehicle:view',
            sort: 2,
            status: 1
          }
        ]
      },
      {
        id: 8,
        parentId: null,
        type: 0,
        title: '系统管理',
        icon: 'el-icon-Setting',
        path: '/system',
        component: '../views/system/SystemView.vue',
        permission: '',
        sort: 8,
        status: 1,
        children: [
          {
            id: 81,
            parentId: 8,
            type: 1,
            title: '用户管理',
            icon: '',
            path: '/system/user',
            component: '../views/system/UserView.vue',
            permission: 'system:user:view',
            sort: 1,
            status: 1
          },
          {
            id: 82,
            parentId: 8,
            type: 1,
            title: '角色管理',
            icon: '',
            path: '/system/role',
            component: '../views/system/RoleView.vue',
            permission: 'system:role:view',
            sort: 2,
            status: 1
          },
          {
            id: 83,
            parentId: 8,
            type: 1,
            title: '部门管理',
            icon: '',
            path: '/system/department',
            component: '../views/system/DepartmentView.vue',
            permission: 'system:department:view',
            sort: 3,
            status: 1
          },
          {
            id: 84,
            parentId: 8,
            type: 1,
            title: '职位管理',
            icon: '',
            path: '/system/position',
            component: '../views/system/PositionView.vue',
            permission: 'system:position:view',
            sort: 4,
            status: 1
          },
          {
            id: 85,
            parentId: 8,
            type: 1,
            title: '菜单管理',
            icon: '',
            path: '/system/menu',
            component: '../views/system/MenuView.vue',
            permission: 'system:menu:view',
            sort: 5,
            status: 1
          }
        ]
      }
    ]

    // 更新菜单选项
    updateMenuOptions()
  } catch (error) {
    console.error('加载菜单列表失败:', error)
    ElMessage.error('加载菜单列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 更新菜单选项
const updateMenuOptions = () => {
  // 只有目录和菜单可以作为父级
  const filterMenus = (menus) => {
    return menus
      .filter(item => item.type !== 2)
      .map(item => {
        const newItem = { ...item }
        if (item.children && item.children.length > 0) {
          newItem.children = filterMenus(item.children)
        }
        return newItem
      })
  }

  // 添加一个顶级选项
  menuOptions.value = [
    { id: null, title: '顶级菜单', children: filterMenus(JSON.parse(JSON.stringify(menuList.value))) }
  ]
}

// 重置表单
const resetForm = () => {
  menuForm.id = null
  menuForm.parentId = null
  menuForm.type = 1
  menuForm.title = ''
  menuForm.icon = ''
  menuForm.path = ''
  menuForm.component = ''
  menuForm.permission = ''
  menuForm.sort = 0
  menuForm.status = 1
}

// 添加菜单
const handleAddMenu = (row) => {
  resetForm()
  dialogTitle.value = '新增菜单'
  
  if (row) {
    menuForm.parentId = row.id
    // 如果父级是目录，默认添加的是菜单
    menuForm.type = row.type === 0 ? 1 : 2
  }
  
  menuDialogVisible.value = true
}

// 编辑菜单
const handleEditMenu = (row) => {
  resetForm()
  dialogTitle.value = '编辑菜单'
  
  // 复制行数据到表单
  Object.keys(menuForm).forEach(key => {
    if (key in row) {
      menuForm[key] = row[key]
    }
  })
  
  menuDialogVisible.value = true
}

// 删除菜单
const handleDeleteMenu = (row) => {
  // 检查是否有子菜单
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该菜单下有子菜单，无法删除')
    return
  }
  
  ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 实际项目中应该调用API删除菜单
      // await deleteMenu(row.id)
      
      // 模拟删除
      deleteMenuById(menuList.value, row.id)
      
      ElMessage.success('删除成功')
      loadMenuList()
    } catch (error) {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败')
    }
  }).catch(() => {})
}

// 递归删除菜单
const deleteMenuById = (menus, id) => {
  for (let i = 0; i < menus.length; i++) {
    if (menus[i].id === id) {
      menus.splice(i, 1)
      return true
    }
    if (menus[i].children && menus[i].children.length > 0) {
      if (deleteMenuById(menus[i].children, id)) {
        return true
      }
    }
  }
  return false
}

// 修改菜单状态
const handleStatusChange = async (row) => {
  try {
    // 实际项目中应该调用API更新菜单状态
    // await updateMenuStatus(row.id, row.status)
    
    ElMessage.success('状态修改成功')
  } catch (error) {
    console.error('修改菜单状态失败:', error)
    ElMessage.error('修改菜单状态失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 保存菜单
const saveMenu = async () => {
  if (!menuFormRef.value) return
  
  try {
    await menuFormRef.value.validate()
    
    // 实际项目中应该调用API保存菜单
    // if (menuForm.id) {
    //   await updateMenu(menuForm)
    // } else {
    //   await createMenu(menuForm)
    // }
    
    // 模拟保存
    if (menuForm.id) {
      // 更新菜单
      updateMenuById(menuList.value, { ...menuForm })
    } else {
      // 新增菜单
      const newMenu = { ...menuForm }
      newMenu.id = Date.now() // 模拟生成ID
      
      if (newMenu.parentId) {
        // 添加到父菜单的children中
        addMenuToParent(menuList.value, newMenu)
      } else {
        // 添加到顶级菜单
        menuList.value.push(newMenu)
      }
    }
    
    ElMessage.success('保存成功')
    menuDialogVisible.value = false
    loadMenuList()
  } catch (error) {
    console.error('保存菜单失败:', error)
    ElMessage.error('保存菜单失败')
  }
}

// 递归更新菜单
const updateMenuById = (menus, updatedMenu) => {
  for (let i = 0; i < menus.length; i++) {
    if (menus[i].id === updatedMenu.id) {
      // 保留children
      const children = menus[i].children
      menus[i] = { ...updatedMenu }
      if (children) {
        menus[i].children = children
      }
      return true
    }
    if (menus[i].children && menus[i].children.length > 0) {
      if (updateMenuById(menus[i].children, updatedMenu)) {
        return true
      }
    }
  }
  return false
}

// 递归添加菜单到父菜单
const addMenuToParent = (menus, newMenu) => {
  for (let i = 0; i < menus.length; i++) {
    if (menus[i].id === newMenu.parentId) {
      if (!menus[i].children) {
        menus[i].children = []
      }
      menus[i].children.push(newMenu)
      return true
    }
    if (menus[i].children && menus[i].children.length > 0) {
      if (addMenuToParent(menus[i].children, newMenu)) {
        return true
      }
    }
  }
  return false
}

// 初始化
onMounted(() => {
  loadMenuList()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.menu-table-card {
  margin-bottom: 20px;
}
</style>
